Check if user belongs to a group in django templates
You can also be interested in:
Generally when implementing some "authentication logic" inside a django template it's enough to check if a user has some permissions, and in such cases you can use the variable perms
, which is available if (from django site):
Technically, these variables are only made available in the template context if you use RequestContext and your "django.contrib.auth.context_processors.auth", which is default. For more, see the RequestContext docs.
But could happen that you need to check if a user belongs to a certain group.
In such case you may find some good custom templatetags like this, they work well and cover all your needs.
Another approach consists in writng a custom template filter and use it with the builtin templatetag if.
I've choosen this way.
So here comes a simple template filter which checks if the user belongs to a given group. It can be easily extended to take into account more groups.
from django import template from django.contrib.auth.models import Group register = template.Library() @register.filter(name='has_group') def has_group(user, group_name): group = Group.objects.get(name=group_name) return True if group in user.groups.all() else False
And in your template you can use it this way:
{% if request.user|has_group:"mygroup" %} <p>User belongs to my group {% else %} <p>User doesn't belong to mygroup</p> {% endif %}
That's quite easy and does what it has to.
Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!
Featured

Django admin and bootstrap 5
Bootstrap 5 has come, currently in beta release, and seems already very stable.
So the question is: are you looking for ...

About code optimization, learn from exercises
Let's see an example of exercise you can face during a job interview, and let's use it to understand some ...

Notes on the Pearson correlation coefficient
The Pearson correlation coefficient is a measure of the linear correlation between two variables X and Y. It has a ...
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May